Pthread Mutex Test

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex_lock=PTHREAD_MUTEX_INITIALIZER;
int g_count;
void* thread_func(void* data){
char* thread_name=(char*)data;
printf("[%s] Ready for Thread\n", thread_name);
sleep(1);
pthread_mutex_lock(&mutex_lock);
printf("[%s] Start Counting\n", thread_name);
for(int i=0;i<1000;i++){
g_count++;
printf("%d\n", g_count);
}
printf("[%s] Finish Counting\n", thread_name);
pthread_mutex_unlock(&mutex_lock);
return NULL;
}
int main(void){
pthread_t p_thread1, p_thread2;
pthread_create(&p_thread1, NULL, thread_func, (void*)"Thread 1");
pthread_create(&p_thread2, NULL, thread_func, (void*)"Thread 2");
printf("\n\nWaiting for Join\n\n");
pthread_join(p_thread1, NULL);
pthread_join(p_thread2, NULL);
printf("pthread exit\n");
pthread_exit(NULL);
}
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex_lock;
void* p_function(void* data){
char* thread_name=(char*)data;
printf("[%s] function start\n", thread_name);
pthread_mutex_lock(&mutex_lock);
sleep(3);
printf("[%s] sleep finish\n", thread_name);
pthread_mutex_unlock(&mutex_lock);
return NULL;
}
int main(void){
pthread_t p1, p2;
pthread_mutex_init(&mutex_lock,NULL);
pthread_create(&p1, NULL, p_function, (void*)"P1");
pthread_create(&p2, NULL, p_function, (void*)"P2");
printf("Join\n");
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Join Finish\n");
pthread_mutex_destroy(&mutex_lock);
return 0;
}
동적 mutex
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t mutex;
int cnt=0;
void *count(void *arg){
int i;
char* name = (char*)arg;
printf("[%s] before\n", name);
pthread_mutex_lock(&mutex);
//======== critical section =============
cnt=0;
for (i = 0; i <10; i++)
{
printf("%s cnt: %d\n", name,cnt);
cnt++;
usleep(1);
}
//========= critical section ============
pthread_mutex_unlock(&mutex);
printf("[%s] finish\n", name);
}
int main()
{
pthread_t thread1,thread2;
pthread_mutex_init(&mutex,NULL);
pthread_create(&thread1, NULL, count, (void *)"thread1");
pthread_create(&thread2, NULL, count, (void *)"thread2");
pthread_join(thread1, NULL);
printf("join thread1 finish\n");
pthread_join(thread2, NULL);
printf("join thread2 finish\n");
pthread_mutex_destroy(&mutex);
}